﻿using API_Service.Common;
using Nancy;
using System.Collections.Generic;
using System.Web;

namespace API_Service.Module
{
    public class CommonModule : BaseAPIModule
    {
        private FileControlService _fileService = new FileControlService();
        public CommonModule() : base("fileupload")
        {
            Get["/"] = _ => Response.AsJson("文件上传API");

            Post["/file/upload"] = _ =>
            {
                var _files = Request.Files;
                var _fileType = Request.Form["file_type"];

                ExecutionResult<dynamic> result = new ExecutionResult<dynamic>();
                List<dynamic> lstFilePath = new List<dynamic>();
                Dictionary<string, string> _lstUpload = new Dictionary<string, string>();

                _lstUpload = _fileService.UploadFile(_files, _fileType);
                if(_lstUpload.Count > 0)
                {
                    result.Status = true;
                    var siteBase = Request.Url.SiteBase;
                    var site = Request.Url.BasePath;
                    siteBase = string.IsNullOrEmpty(site) ? siteBase : siteBase + site;
                    foreach (string vKey in _lstUpload.Keys)
                    {
                        lstFilePath.Add(siteBase + _lstUpload[vKey].ToString());                        
                    }
                   
                    result.Datas = lstFilePath.ToArray();
                }
                else
                {
                    result.Status = false;
                    result.Message = "Upload file fail. please check.";
                }
                return Response.AsJson(result);
            };

            Post["/file/delete"] = _ =>
            {
                var _file = Request.Form["file_path"];
                ExecutionResult<dynamic> result;
                result = new ExecutionResult<dynamic>();

                result = _fileService.DeleteFile(_file, Request.Url.SiteBase);

                return Response.AsJson(result);
            };
        }        
    }
}